package yifeng.thread;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 限制 只有3个线程访问资源
 * @author pengyifeng
 *
 */
public class T326 {
	
	public static Object data = "data";
	
	public static AtomicInteger ai = new AtomicInteger(0);
	
	public static Lock lock = new ReentrantLock();
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		CopyOnWriteArrayList s;
		
		final Condition c1 = lock.newCondition();
		
		for(int i = 0; i < 100; i++){
			new Thread(new Runnable(){
				@Override
				public void run() {
					lock.lock();
					while(ai.get() >= 3){
						try {
							c1.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					ai.incrementAndGet();
					lock.unlock();
					
					System.out.println(Thread.currentThread().getName() + " : " + ai.get());
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					ai.decrementAndGet();
					
					
					lock.lock();
					c1.signal();
					lock.unlock();
				}
			}, "Thread " + i).start();
		}
	}

}
